import { createStore } from 'vuex';
import { wsClient } from '@/utils/websocket';

export default createStore({
  state: {
    notifications: [],
    unreadCount: 0
  },
  
  mutations: {
    ADD_NOTIFICATION(state, notification) {
      state.notifications.unshift(notification);
      state.unreadCount++;
    },
    SET_NOTIFICATIONS(state, notifications) {
      state.notifications = notifications;
    },
    SET_UNREAD_COUNT(state, count) {
      state.unreadCount = count;
    },
    MARK_AS_READ(state, notificationId) {
      const notification = state.notifications.find(n => n.id === notificationId);
      if (notification && !notification.is_read) {
        notification.is_read = true;
        state.unreadCount = Math.max(0, state.unreadCount - 1);
      }
    }
  },
  
  actions: {
    // 初始化WebSocket连接
    initWebSocket({ commit }, token) {
      wsClient.connect(token);
      
      // 注册消息处理
      wsClient.onMessage((message) => {
        if (message.type === 'notification') {
          commit('ADD_NOTIFICATION', {
            ...message.data,
            is_read: false
          });
        }
      });
    },
    
    // 获取通知列表
    async fetchNotifications({ commit }) {
      try {
        const response = await fetch('/api/notifications', {
          headers: {
            'Authorization': `Bearer ${localStorage.getItem('token')}`
          }
        });
        const data = await response.json();
        
        if (data.code === 200) {
          commit('SET_NOTIFICATIONS', data.data);
          commit('SET_UNREAD_COUNT', data.data.filter(n => !n.is_read).length);
        }
      } catch (error) {
        console.error('获取通知列表失败:', error);
      }
    },
    
    // 标记通知为已读
    async markAsRead({ commit }, notificationId) {
      try {
        const response = await fetch(`/api/notifications/${notificationId}/read`, {
          method: 'POST',
          headers: {
            'Authorization': `Bearer ${localStorage.getItem('token')}`
          }
        });
        const data = await response.json();
        
        if (data.code === 200) {
          commit('MARK_AS_READ', notificationId);
        }
      } catch (error) {
        console.error('标记通知已读失败:', error);
      }
    }
  }
}); 